class Node < ServerSide::Model
  # relationships
  one_to_one :parent, :class => Node, :key => :parent_id
  # the default :key is the property name (parent) plus _id postfix
  # generates proc {Node[@values[:parent_id]] if @values[:parent_id]}
  
  one_to_many :children, :class => Node, :key => {:parent_id => :id}
  # generates proc {Node.filter(:parent_id => @values[:id])}
  
  one_to_one :producer, :class => Channel, :key => :producer_id
  # here as well the :key can be ommited
  # generates proc {Channel[@values[:producer_id]] if @values[:producer_id]}
  
  query :consumers {Channels.consuming_node(@id)}
  
  query :derivatives do
    Node.join(:expr_refs, :target_id => :id).
      filter(:expr_refs__source_id => @values[:id])
  end
  
  # or...
  
  many_to_many :derivatives, :class => Node, 
    :through => :expr_refs, :key => {:source_id => :target_id}
  
  def self.[](arg)
    case arg
    when String: find_by_path(arg)
    else find_by_id(arg)
    end
  end
  
  def self.create(path)
    path.match /(.+)?\/([^\/]*)$/
    parent_path = $1 || "/"
    node_name = $2

    if (node_name != "")
      parent = find_by_path(parent_path)
      new_node = create(
        :name => node_name,
        :path => path,
        :parent_id => parent[:id],
        :producer_id => parent[:producer_id],
        :config => parent[:config],
        :sample_rate => parent[:sample_rate],
        :logged => parent[:logged]
      )
      new_node.set_attributes(parent.get_attributes)
      new_node.update_tracking
      new_node
    else
      create(
        :name => node_name,
        :path => path,
        :logged => 1
      )
    end
  end
end